import Navbar from "@/components/Navbar";
import { showToast, navigateTo } from "@tarojs/taro";
import { Image, Text, View } from "@tarojs/components";
import arrowImg from "@/static/images/icon/arrow-right.png";
import "./index.less";
import { useState } from "react";
import ImageConstant from "@/constant/ImageConstant";
import { CommonUtil } from "@/utils/CommonUtil";
import { Form, ImagePreview, Input, Uploader } from "@nutui/nutui-react-taro";
import CodeConstant from "@/constant/CodeConstant";
import useIdentity from "@/hooks/useIdentity";
import authStore from "@/stores/AuthStore";
import userStore from "@/stores/UserStore";
import { observer } from "mobx-react-lite";
import ImageComp from "@/components/Image";
import BusinessConstant from "@/constant/BusinessConstant";
import ImageIcon from "@/components/ImageIcon";
import Popup from "@/components/Popup";
import systemStore from "@/stores/SystemStore";

function selfInfo() {
  const { NORMAL, STOP_USING, DELETE, UN_IDENTITY } = BusinessConstant;
  const { user, setUser } = userStore;
  const { systemConfig } = systemStore;
  // 用户头像预览
  const [imagePreview, setImagePreview] = useState(false);
  // 修改名字popup
  const [modifyNameVisible, setModifyNameVisible] = useState(false);
  // form表单实例
  const [form] = Form.useForm();

  const { getUserInfo, uploadUserHeadImgUrl, updateUser } = useIdentity();
  /**
   * 获取状态标签的背景色
   */
  const getStatusBgColor = (status: number) => {
    switch (status) {
      // 正常
      case NORMAL:
        return "normal";
      // 停用
      case STOP_USING:
        return "stop-using";
      // 删除
      case DELETE:
        return "delete";
      // 未实名
      case UN_IDENTITY:
        return "stop-using";
    }
  };

  /**
   * 获取状态标签的文字
   * @param status 状态
   */
  const getStatusText = (status: number) => {
    switch (status) {
      // 正常
      case NORMAL:
        return "正常";
      // 停用
      case STOP_USING:
        return "停用";
      // 删除
      case DELETE:
        return "删除";
      // 未实名
      case UN_IDENTITY:
        return "未实名";
    }
  };

  /**
   * 上传头像成功回调
   */
  const headImgUploadSuccess = ({ responseText }) => {
    const res = JSON.parse(responseText.data);
    if (res.code !== CodeConstant.SUCCESS) {
      showToast({ title: "头像上传失败！", icon: "error" });
      return;
    }
    // 发送请求获取用户信息
    getUserInfo();
    showToast({ title: "头像上传成功！", icon: "success" });
  };

  /**
   * 处理确定修改名字
   */
  const handleConfirm = async () => {
    let updateUserName: string;
    try {
      updateUserName = form.getFieldValue("name");
    } catch (_) {
      // 值跟原来一样会报错
      showToast({ title: "保存成功", icon: "success" });
      setModifyNameVisible(false);
      return;
    }
    const res: any = await updateUser({ name: updateUserName });
    setUser(res);
    setModifyNameVisible(false);
    showToast({ title: "保存成功", icon: "success" });
  };

  return (
    <Navbar
      mode="back"
      title="个人中心"
      bgColor="var(--mini-first)"
      className="self-info-container"
    >
      <View className="show-wrap">
        <View className="info-item header-img-item">
          <Uploader
            url={uploadUserHeadImgUrl}
            maxCount={1}
            headers={{ authorization: authStore.token }}
            onSuccess={headImgUploadSuccess}
            className="uploader-wrap"
          >
            <Text className="text">头像</Text>
            <ImageComp
              src={user?.headImg}
              onClick={() => setImagePreview(true)}
              className="header-img"
            />
            <Image src={arrowImg} className="arrow-icon" />
          </Uploader>
        </View>
        <View className="info-item" onTap={() => setModifyNameVisible(true)}>
          <Text className="text">名字</Text>
          <Text className="item-content">{user?.name}</Text>
          <Image src={arrowImg} className="arrow-icon" />
        </View>
        <View className="info-item">
          <Text className="text">手机号</Text>
          <Text className="item-content">{user?.phone}</Text>
        </View>
        <View className="info-item">
          <Text className="text">注册时间</Text>
          <Text className="item-content">
            {CommonUtil.formatUtcTime(user?.createdAt)}
          </Text>
        </View>
        <View className="info-item">
          <Text className="text">最近修改时间</Text>
          <Text className="item-content">
            {CommonUtil.formatUtcTime(user?.updatedAt)}
          </Text>
        </View>
      </View>
      {systemConfig.verificationEntry === 1 && (
        <>
          <View className="info-wrap">
            <View className="info-item">
              <Text className="text">状态</Text>
              <View className="item-content">
                <View
                  className={`status-tag ${getStatusBgColor(user?.status!)}`}
                >
                  {getStatusText(user?.status!)}
                </View>
              </View>
            </View>
            {/* 实名信息 */}
            {user?.status === NORMAL && (
              <>
                <View className="info-item">
                  <Text className="text">姓名</Text>
                  <Text className="item-content">{user?.identityName}</Text>
                </View>
                <View className="info-item">
                  <Text className="text">性别</Text>
                  <Text className="item-content">
                    {user?.identitySex ? "男" : "女"}
                  </Text>
                </View>
                <View className="info-item">
                  <Text className="text">民族</Text>
                  <Text className="item-content">{user?.identityNation}</Text>
                </View>
                <View className="info-item">
                  <Text className="text">身份证号码</Text>
                  <Text className="item-content">{user?.identityNumber}</Text>
                </View>{" "}
                <View className="info-item">
                  <Text className="text">身份证所在地</Text>
                  <Text className="item-content">{user?.identityAddress}</Text>
                </View>
              </>
            )}
          </View>
          {/* 实名入口 */}
          {user?.status === UN_IDENTITY && (
            <View className="info-wrap">
              <View
                className="info-item"
                onClick={() =>
                  navigateTo({ url: "/pages/identityVerification/index" })
                }
              >
                <Text className="mr-4">去实名</Text>
                <ImageIcon
                  src="/un-identity-icon.png"
                  className="icon"
                ></ImageIcon>
              </View>
            </View>
          )}
        </>
      )}
      <ImagePreview
        images={[{ src: `${ImageConstant.SERVER_ROOT}/${user?.headImg}` }]}
        visible={imagePreview}
        onClose={() => setImagePreview(false)}
      />
      <Popup
        visible={modifyNameVisible}
        onClose={() => setModifyNameVisible(false)}
        onConfirm={handleConfirm}
        title="更改名字"
      >
        <Form form={form}>
          <Form.Item name="name" initialValue={user?.name}>
            <Input placeholder="请输入你的名字" type="text"></Input>
          </Form.Item>
        </Form>
        <View className="explain">好的名字可以让对方更容易记住你。</View>
      </Popup>
    </Navbar>
  );
}

export default observer(selfInfo);
